package tests;

import java.util.Date;
import java.util.Random;

public class Chat {

    private static class Counter {
        private int count;
        private int max;

        public int getCount() {
            return count;
        }

        public int getMax() {
            return max;
        }

        public synchronized void incCount() {
            ++count;
            ++max;
        }

        public synchronized void decCount() {
            --count;
        }
    }

    private static class ChatTread implements Runnable {

        private final long wait;
        private final Counter counter;
        private final String ThreadName;


        public ChatTread(String ThreadName,long wait, Counter counter) {
            this.wait = wait;
            this.counter = counter;
            this.ThreadName = ThreadName;
        }

        @Override
        public void run() {

            counter.incCount();
            System.out.format("%s: is inc Count = %s, time - %s, wait - %s%n",
                    ThreadName, counter.getCount(), System.currentTimeMillis(), wait);
            try {
                Thread.sleep(wait); //it is like making some process
            } catch (InterruptedException e) {
                System.out.format("%s: is interrupt %s%n",
                        ThreadName, new Date(System.currentTimeMillis()));
            } finally {
                counter.decCount();
                System.out.format("%s: is dec Count = %s, time - %s%n",
                        ThreadName, counter.getCount(), System.currentTimeMillis());
            }


        }
    }

    public static void main(String[] args) {
        int threadsCount = 1000;
        Counter c = new Counter();

        for (int i=1; i <= threadsCount; ++i) {
            Random r = new Random();
            Thread last = new Thread(new ChatTread(String.valueOf(i), r.nextInt(10000) + 1, c));
            last.start();
        }

        while (c.getMax() == 0 || c.getCount() != 0) {
        }
        System.out.println("Main: counter is 0, max is " + c.getMax() + ", program is finished!!!");
    }
}
